package ui;

import java.awt.Color;
import java.awt.Component;

import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.border.LineBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import storage.DataManager;

public class Tree 
{
	private DefaultMutableTreeNode rootNode;
	private DefaultTreeModel treeModel;
	private DefaultMutableTreeNode parentDynamic;
	private DefaultMutableTreeNode childDynamic;
	private JTree tree;

	public Tree() {
		rootNode = new DefaultMutableTreeNode("ToDo");
		treeModel = new DefaultTreeModel(rootNode);
		tree = new JTree(treeModel);
		tree.setBorder(new LineBorder(new Color(0, 0, 139), 2));
		tree.setEditable(true);
		tree.setRootVisible(false);
		tree.setShowsRootHandles(true);
		ImageIcon root = new ImageIcon("images/right.gif");
		
			
		ImageIcon leafIcon = createImageIcon("images/right.gif");
		if (leafIcon != null) {
			DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
			renderer.setLeafIcon(leafIcon);			
			tree.setCellRenderer(renderer);
		} else {
			System.err.println("Leaf icon missing; using default.");
		}
		
		populateTree();
	}

	//TODO Implement
	public void clearTree() {
		
	}
	
	public void populateTree() {
		DefaultMutableTreeNode child = null;
		DefaultMutableTreeNode parent;
		String names[] = DataManager.getListNames();
		String events[];

		for (int i = 0; i < names.length; i++) {
			parent = new DefaultMutableTreeNode(names[i]);
			rootNode.add(parent);
			events = DataManager.getEventsInList(names[i]);
			for (int j = 0; j < events.length; j++) {
				child = new DefaultMutableTreeNode(events[j]);
				parent.add(child);
			}
		}
		treeModel.reload();
	}
	public void addtoTree()
	{
		
	}

	/** Returns an ImageIcon, or null if the path was invalid. */
	protected static ImageIcon createImageIcon(String path) {
		java.net.URL imgURL = Tree.class.getResource(path);
		if (imgURL != null) {
			return new ImageIcon(imgURL);
		} else {
			System.err.println("Couldn't find file: " + path);
			return null;
		}
	}

	public JTree getTreeComponent() {
		// TODO Auto-generated method stub
		return tree;
	}
}
